# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/7/29'
# __name__ = 'fields.py'

from django.db import models
from django.conf import settings
from utils.signer_helper import Signer
signer = Signer(settings.SECRET_KEY)
# Create your models here.

class EncryptCharField(models.CharField):
    # def to_python(self, value):
    #     if isinstance(value, str) or value is None:
    #         return value
    #     return str(value)

    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        newvalue = signer.sign(value)
        return self.to_python(newvalue)

    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        newvalue = signer.unsign(value)
        return newvalue


class EncryptTextField(models.TextField):
    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        newvalue = signer.sign(value)
        return self.to_python(newvalue)

    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        newvalue = signer.unsign(value)
        return newvalue